package com.qdd01.interception;

import com.qdd01.entity.User;
import com.qdd01.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Component
public class WebSocketInterceptor implements HandshakeInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketInterceptor.class);

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        try {
            if (request instanceof ServletServerHttpRequest) {
                ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;

                // 从 URL 参数中获取 token
                String token = servletRequest.getServletRequest().getParameter("token");
                logger.info("WebSocket连接token: {}", token);

                if (token != null && !token.isEmpty()) {
                    // 如果使用了 Bearer 认证方案，需要去掉 "Bearer " 前缀
                    if (token.startsWith("Bearer ")) {
                        token = token.substring(7);
                    }

                    try {
                        // 使用相同的 JWT 验证逻辑
                        User user = JwtUtil.extractUser(token);
                        // 将用户信息存储在 WebSocket session 的属性中
                        attributes.put("userId", user.getId());
                        attributes.put("user", user);
                        logger.info("WebSocket连接用户ID: {}", user.getId());
                        return true;
                    } catch (Exception e) {
                        logger.error("Token验证失败", e);
                        return false;
                    }
                } else {
                    logger.warn("WebSocket连接未提供token");
                    return false;
                }
            }
            return false;
        } catch (Exception e) {
            logger.error("WebSocket握手失败", e);
            return false;
        }
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception exception) {
        // 握手后的处理
    }
}